<?php

namespace App\Admin\Actions\GoldRecordAction;

use App\Models\GoldRecord;
use App\Models\User;
use App\Models\GoldProduct;
use Illuminate\Http\Request;
use App\Supports\Withdraw\Withdrawer;
use App\Services\ApplyGoldRecordBatchExamine\ApplyGoldRecordBatchExamine;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Collection;
use App\Services\CloseUnpaidStorm\CloseUnpaidStorm;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;

class CloseRecord extends RowAction
{
	public $name = '取消记录';

	public function handle(GoldRecord $model)
	{
		if ($model->isClosed()) {
		    return $this->response()->error('目标订单已关闭');
	    }elseif ($model->isPaid()) {
		    return $this->response()->error('目标订单已支付');
	    }elseif (!$model->goldRecordVoucher()) {
		    return $this->response()->error('目标订单未上传凭证');
		}elseif (!$model->up_gold_record_id) {
		    return $this->response()->error('目标订单没有上级寄售来源');
	    }elseif (!$model->is_contact) {
		    return $this->response()->error('目标订单未主动联系客服');
	    }  


	    $user = User::find($model->user_id);

	    if($user){
	    	app(CloseUnpaidStorm::class, [
		    	'uid' => $model->user_id,
			    'unpaidCacheId' => $model->cache_id
		    ])->close();

	    }else{
	    	 $record = GoldRecord::find(Redis::hGet($model->cache_id, 'gold_record_id'));
	    	 $record->update(['closed_at' => Carbon::now()]);
	    	 $rid = Redis::hGet($model->cache_id, 'gold_round_id');
			 $pid = Redis::hGet($model->cache_id, 'gold_product_id');
			 //dd($pid);
			 GoldProduct::sDelFromSoldCache($pid, $rid);
			 GoldProduct::sAddToAliveCache($pid, $rid);

			//Redis::zRem("user_{$model->user_id}_unpaid_gold_records", $model->chche_id);
			
			Redis::del($model->chche_id);
	    }
	 

		return $this->response()->success('取消成功')->refresh();
	}

	public function dialog()
	{
		$this->confirm('确定取消当前记录，谨慎操作?');
	}
}
